/*  
 * cafe-player.js
 * @Author :      GUORUI
 * @CreateDate :  2018年1月31日
 * Copyright (c) 2018, NRIET.　
 * 时间轴控件
 */

;define(function(){
	//创建主界面
	function bulidHtml(cfg){
		var $warp = $('<div>');
		$warp.addClass("cafe-player");
		style($warp,cfg);
        bulidTimeLabel($warp,cfg);
		return $warp;
	}
	function style($warp,cfg){
		var $showBtn = $('<div>').addClass("cafe-p-showbtn");
		var $time = $('<div>').addClass("cafe-p-time");
		bulidTime($time,cfg);
		$warp.append($showBtn).append($time);
		return $warp;
	}
	function bulidTime($time,cfg){
		var $smooth = $('<section>').addClass("cafe-p-smooth");
		var $sts = $('<div>').addClass("cafe-p-sts");
		var $tsel = $('<div>').addClass("cafe-p-sts-tselect");
		var $tlabel = $('<div>').addClass("cafe-p-sts-tlabel");
		$tlabel.append($('<span>').addClass("cafe-p-sts-tl-icon"));
		switch(cfg.timeInterval){
			//当时间间隔为5或6分钟或10分钟时，默认1小时
			case 5:
			case 6:
			case 10:
				$tlabel.append($('<span>').attr("tmid",6).addClass("cafe-p-sts-tl-name").text("6小时"));
				break;
			//当时间间隔为15分钟时，默认3小时
			case 15:
				$tlabel.append($('<span>').attr("tmid",3).addClass("cafe-p-sts-tl-name").text("3小时"));
				break;
			//当时间间隔为30分钟时，默认6小时
			case 30:
				$tlabel.append($('<span>').attr("tmid",6).addClass("cafe-p-sts-tl-name").text("6小时"));
				break;
			//当时间间隔为1小时时，默认12小时
			case 1*60:
				$tlabel.append($('<span>').attr("tmid",12).addClass("cafe-p-sts-tl-name").text("12小时"));
				break;
			 //当时间间隔为3小时时，默认24小时
			case 3*60:
				$tlabel.append($('<span>').attr("tmid",24).addClass("cafe-p-sts-tl-name").text("24小时"));
				break;
			//当时间间隔为6小时时，默认72小时
			case 6*60:
				$tlabel.append($('<span>').attr("tmid",72).addClass("cafe-p-sts-tl-name").text("72小时"));
				break;
			//当时间间隔为12或24小时时，默认7天
			case 12*60:
			case 24*60:
				$tlabel.append($('<span>').attr("tmid",7*24).addClass("cafe-p-sts-tl-name").text("7天"));
				break;
		}
		$sts.append($tsel).append($tlabel);
		var $sta = $('<div>').addClass("cafe-p-sta");
		var $ta = $('<div>').addClass("cafe-p-sta-timearea");
		$ta.append($('<div>').addClass("cafe-p-sta-t-tip").append($('<span>')))
		   .append($('<div>').addClass("cafe-p-sta-t-slider"))
		   .append($('<div>').addClass("cafe-p-sta-t-bg"))
		   .append($('<div>').addClass("cafe-p-sta-t-defbg"));
		var $tl = $('<div>').addClass("cafe-p-sta-timelabel");
		$sta.append($ta).append($tl);
		$smooth.append($sts).append($sta);
		var $timeControl = $('<div>').addClass("cafe-p-timecontrol");
		$timeControl.append($('<span>').addClass("cafe-p-left-icon"))
					.append($('<span>').addClass("cafe-p-play-icon"))
					.append($('<span>').addClass("cafe-p-right-icon"));
        var $hideBtn = $('<span>');
        $hideBtn.addClass("cafe-p-hidebtn").append($('<i>').addClass("cafe-ifont cafe-ic-xiangzuoutotheleft"));
        $timeControl.append($hideBtn);
		$time.append($smooth).append($timeControl);
	}
	/**
	 * 播放
	 */
	function play($drop,cfg){
		clearInterval($drop.find(".cafe-p-play-icon").val());
		var ti = $drop.find(".cafe-p-sts-tl-name").attr("tmid") * 60;
		var bgW =  $drop.find(".cafe-p-sta-t-defbg").width();
		var per = ti / bgW;
		var frameNumber = 60;
		var step = (parseFloat($drop.find(".cafe-p-sta-timelabel>span:eq(1)").css("margin-left")) + 32) / frameNumber;
		var avgss = 1000/frameNumber;
		var interval = setInterval(function(){
			if(0 == $drop.length){
				clearInterval(interval);
			}
			var $tip = $drop.find(".cafe-p-sta-t-tip");
			var $slider = $drop.find(".cafe-p-sta-t-slider");
			var sliderleft = parseFloat($slider.css("left")) + step;
			if(sliderleft >= bgW - 12){
				sliderleft = -12;
			}
			$slider.css("left", sliderleft + "px").siblings(".cafe-p-sta-t-bg").css("width",(sliderleft + 12) + "px");
			var time = new Date($drop.find(".cafe-p-sta-timelabel").find("span:first").attr("time"));
			time.setMinutes(time.getMinutes() + Math.round((sliderleft + 12) * per));
			$tip.css("left",(sliderleft - 52) + "px").find("span").text(time.format("hh:mm"));

            GIS.GridShow.animate(cfg.gisId,cfg.layerIds,cfg.timesArr,time.getTime());
		}, avgss);

		$drop.find(".cafe-p-play-icon").val(interval);
	}
	/**
	 * 创建时长选择界面
	 */
	function bulidDuration(cfg){
		var $duration = $('<div>').addClass("cafe-p-d-container");
		var $d1 = $('<div>').addClass("cafe-p-d-line");
		var $d2 = $('<div>').addClass("cafe-p-d-line");
		var $d3 = $('<div>').addClass("cafe-p-d-line");
		switch(cfg.timeInterval){
			//当时间间隔为5或6分钟时，可选1/3/6/12/24/48/72小时
			case 5:
			case 6:
				$d1.append($('<span>').attr("sid",1).text("1h"))
				   .append($('<span>').attr("sid",3).text("3h"))
				   .append($('<span>').attr("sid",6).addClass("active").text("6h"));
				$d2.append($('<span>').attr("sid",12).text("12h"))
				   .append($('<span>').attr("sid",24).text("24h"));
				$d3.append($('<span>').attr("sid",48).text("48h"))
				   .append($('<span>').attr("sid",72).text("72h"));
				$duration.append($d1).append($d2).append($d3);
				break;
			//当时间间隔为10分钟时，可选2/3/6/12/24/48/72小时
			case 10:
				$d1.append($('<span>').attr("sid",1).text("1h"))
				   .append($('<span>').attr("sid",3).text("3h"))
				   .append($('<span>').attr("sid",6).addClass("active").text("6h"));
				$d2.append($('<span>').attr("sid",12).text("12h"))
				   .append($('<span>').attr("sid",24).text("24h"));
				$d3.append($('<span>').attr("sid",48).text("48h"))
				   .append($('<span>').attr("sid",72).text("72h"));
				$duration.append($d1).append($d2).append($d3);
				break;
			//当时间间隔为15分钟时，可选3/6/12/24/48/72小时
			case 15:
				$d1.append($('<span>').attr("sid",3).addClass("active").text("3h"))
				   .append($('<span>').attr("sid",6).text("6h"));
				$d2.append($('<span>').attr("sid",12).text("12h"))
				   .append($('<span>').attr("sid",24).text("24h"));
				$d3.append($('<span>').attr("sid",48).text("48h"))
				   .append($('<span>').attr("sid",72).text("72h"));
				$duration.append($d1).append($d2).append($d3);
				break;
			//当时间间隔为30分钟时，可选6/12/24/48/72小时
			case 30:
				$d1.append($('<span>').attr("sid",6).addClass("active").text("6h"))
				   .append($('<span>').attr("sid",12).text("12h"))
				   .append($('<span>').attr("sid",24).text("24h"));
				$d2.append($('<span>').attr("sid",48).text("48h"))
				   .append($('<span>').attr("sid",72).text("72h"));
				$duration.css("height","69px").append($d1).append($d2);
				break;
			//当时间间隔为1小时时，可选12/24/48/72小时
			case 1*60:
				$d1.append($('<span>').attr("sid",12).addClass("active").text("12h"))
				   .append($('<span>').attr("sid",24).text("24h"));
				$d2.append($('<span>').attr("sid",48).text("48h"))
				   .append($('<span>').attr("sid",72).text("72h"));
				$duration.css("height","69px").append($d1).append($d2);
				break;
			 //当时间间隔为3小时时，可选24/48/72小时
			case 3*60:
				$d1.append($('<span>').attr("sid",24).addClass("active").text("24h"))
				   .append($('<span>').attr("sid",48).text("48h"))
				   .append($('<span>').attr("sid",72).text("72h"));
				$duration.css("height","37px").append($d1);
				break;
			//当时间间隔为6小时时，可选72小时
			case 6*60:
				$d1.append($('<span>').attr("sid",72).addClass("active").text("72h"));
				$duration.css("height","37px").append($d1);
				break;
			//当时间间隔为12或24小时时，可选7天
			case 12*60:
			case 24*60:
				$d1.append($('<span>').attr("sid",7*24).addClass("active").text("7天"));
				$duration.css("height","37px").append($d1);
				break;
		}
		var $d4 = $('<div>').addClass("cafe-p-d-sanjiao");
		$duration.append($d4);
		
		$duration.off().on("click",".cafe-p-d-line>span",function(){
			if(!$(this).hasClass("active")){
				var $dc = $(this).closest(".cafe-p-d-container");
				$dc.find(".cafe-p-d-line>span").removeClass("active");
				$(this).addClass("active");
				$dc.siblings(".cafe-player").find(".cafe-p-sts-tl-name").attr("tmid",$(this).attr("sid")).text($(this).attr("sid") + "小时");
				$dc.siblings(".cafe-player").find(".cafe-p-sta-t-tip,.cafe-p-sta-t-slider,.cafe-p-sta-t-bg").removeAttr("style");
				var $play = $dc.siblings(".cafe-player").find(".cafe-p-play-icon");
				if($play.hasClass("active")){
					$play.click();
				}
				bulidTimeLabel($dc.siblings(".cafe-player"),cfg);
			}
		});
		return $duration;
	}
	/**
	 * 创建时间刻度
	 */
	function bulidTimeLabel($drop,cfg){
		var $timelabel = $drop.find(".cafe-p-sta-timelabel");
		$timelabel.empty();
		var curtime = new Date(cfg.time);
		$drop.find(".cafe-p-sta-t-tip>span").text(curtime.format("hh:mm"));
		var mintime = new Date(cfg.time);
		var duration = $drop.find(".cafe-p-sts-tl-name").attr("tmid") * 60;
		mintime.setMinutes(mintime.getMinutes() - duration);
		var timeInterval = getSmoothti(duration)[0];
		$timelabel.append($('<span>').attr("time",mintime).append($("<span>").addClass("cafe-p-sta-label").text(mintime.format("hh:mm"))));
		while (curtime.getTime() > mintime.getTime()){
			mintime.setMinutes(mintime.getMinutes() + timeInterval);
			var $span = $('<span>').attr("time",mintime).append($("<span>").addClass("cafe-p-sta-label").text(mintime.format("hh:mm")));
			$timelabel.append($span);
		}
	}
	//获取播放数据时间数组
	function getPlayDataTimeArr($drop){
		var $lastTime = $drop.find(".cafe-p-sta-timelabel>span:last");
		var curtime = new Date($lastTime.attr("time"));
		var mintime = new Date($lastTime.attr("time"));
		var duration = $drop.find(".cafe-p-sts-tl-name").attr("tmid") * 60;
		mintime.setMinutes(mintime.getMinutes() - duration);
		var dtimeInterval = getSmoothti(duration)[1];
		var timeArr = [];
		while (curtime.getTime() >= mintime.getTime()) {
			timeArr.push(mintime.format("yyyyMMddhhmmss"));
			mintime.setMinutes(mintime.getMinutes() + dtimeInterval);
		}
		return timeArr;
	}
	//平滑时间轴上时间刻度间隔和数据时间间隔
	function getSmoothti(t){
		switch (t) {
			case 1*60:
				return [10,5];
			case 3*60:
				return [30,15];
			case 6*60:
				return [60,30];
			case 12*60:
				return [2*60,60];
			case 24*60:
				return [4*60,2*60];
			case 48*60:
				return [8*60,4*60];
			case 72*60:
				return [12*60,6*60];
			case 7*24*60:
				return [24*60,24*60];
		}
	}
	/**
	 * 绑定事件
	 */
	function _eves($drop,cfg){
		$drop.off().on("click",".cafe-ic-xiangzuoutotheleft",function(){//隐藏
			$(this).closest(".cafe-p-time").fadeOut().siblings(".cafe-p-showbtn").show();
		}).on("click",".cafe-p-showbtn",function(){//显示
            $(this).hide().siblings(".cafe-p-time").fadeIn();
		}).on("click",".cafe-p-left-icon",function(){//点击向左
			var $slider = $(".cafe-p-sta-t-slider");
			var bgW =  $drop.find(".cafe-p-sta-t-defbg").width();
			var $tip = $drop.find(".cafe-p-sta-t-tip");
			var timeArr = getPlayDataTimeArr($drop);
			var duration = $drop.find(".cafe-p-sts-tl-name").attr("tmid") * 60;
			var timeInterval = getSmoothti(duration)[1];
			var step = bgW / (duration / timeInterval);
			var curLeft = parseFloat($slider.css("left")) - step;
			var index = Math.ceil(curLeft/step);
			if(curLeft <= -12){
				index = 0;
			}
			var curWidth = index * step;
			$slider.css("left",(curWidth - 12) + "px").siblings(".cafe-p-sta-t-bg").css("width",curWidth + "px");
			var time = new Date(dateUtil.convertStringToDate7(timeArr[index],"yyyy-MM-dd hh:mm:ss"));
			$tip.css("left",(curWidth - 64) + "px").find("span").text(time.format("hh:mm"));

            GIS.GridShow.animate(cfg.gisId,cfg.layerIds,cfg.timesArr,time.getTime());
		}).on("click",".cafe-p-play-icon",function(e){//点击播放
			e.stopPropagation();
			if($(this).hasClass("active")){
				if(GLMap.getLayer('boundaryLayerId')){
					GLMap.getLayer('boundaryLayerId').visible=true;
				}
				$(this).removeClass("active");
				$(this).find("i.cafe-ifont").remove();
				clearInterval($(this).val());
			}else{
                if(0 == cfg.timesArr.length && $.isFunction(cfg.callPlay)){
                    cfg.callPlay(getPlayDataTimeArr($drop));
                }
				if(GLMap.getLayer('boundaryLayerId')){
					GLMap.getLayer('boundaryLayerId').visible=false;
				}
				$(this).addClass("active");
				$(this).append($('<i>').addClass("cafe-ifont cafe-ic-zanting"));
				play($drop,cfg);
			}
		}).on("click",".cafe-p-right-icon",function(){//点击向右
			var $slider = $(".cafe-p-sta-t-slider");
			var bgW =  $drop.find(".cafe-p-sta-t-defbg").width();
			var $tip = $drop.find(".cafe-p-sta-t-tip");
			var timeArr = getPlayDataTimeArr($drop);
			var duration = $drop.find(".cafe-p-sts-tl-name").attr("tmid") * 60;
			var timeInterval = getSmoothti(duration)[1];
			var step = bgW / (duration / timeInterval);
			var curLeft = parseFloat($slider.css("left")) + step;
			var index = Math.ceil(curLeft/step);
			if(curLeft >= bgW - 12){
				index = timeArr.length - 1;
			}
			var curWidth = index * step;
			$slider.css("left",(curWidth - 12) + "px").siblings(".cafe-p-sta-t-bg").css("width",curWidth + "px");
			var time = new Date(dateUtil.convertStringToDate7(timeArr[index],"yyyy-MM-dd hh:mm:ss"));
			$tip.css("left",(curWidth - 64) + "px").find("span").text(time.format("hh:mm"));

            GIS.GridShow.animate(cfg.gisId,cfg.layerIds,cfg.timesArr,time.getTime());
		}).on("click",".cafe-p-sts-tselect",function(){//显示时长选择
			if($(this).hasClass("active")){
				$(this).removeClass("active");
				$drop.siblings(".cafe-p-d-container").hide();
			}else{
				$(this).addClass("active");
				if(!$drop.siblings(".cafe-p-d-container").is(":hidden")){
					$drop.before(bulidDuration(cfg));
				}else{
					$drop.siblings(".cafe-p-d-container").show();
				}
			}
		}).on("mousedown",".cafe-p-sta-t-slider",function(event){//拖动滑块
			var left = parseFloat($(this).css("left"));
			var that = this;
			var ti = $drop.find(".cafe-p-sts-tl-name").attr("tmid") * 60;
			var bgW =  $(this).siblings(".cafe-p-sta-t-defbg").width();
			var per = ti / bgW;
			window.document.onmousemove = function(ev){
				ev.preventDefault();
				var step = 1;
				var $tip = $(that).siblings(".cafe-p-sta-t-tip");
				var offset = ev.pageX-event.pageX;
				var _left = left + Math.round(offset / step) * step;
				if(_left <= -12){
					_left = -12;
				}else if(_left >= bgW - 12){
					_left = bgW - 12;
				}
				$(that).css("left",_left + "px").siblings(".cafe-p-sta-t-bg").css("width",(_left + 12) + "px");
				var time = new Date($drop.find(".cafe-p-sta-timelabel").find("span:first").attr("time"));
				time.setMinutes(time.getMinutes() + Math.round((_left + 12) * per));
				$tip.css("left",(_left - 52) + "px").find("span").text(time.format("hh:mm"));

                GIS.GridShow.animate(cfg.gisId,cfg.layerIds,cfg.timesArr,time.getTime());
			};
			window.document.onmouseup = function(){
				window.document.onmousemove = null;
				window.document.onmouseup = null;
			};
		});
	}

	var CFPlayer = function(settings){
		var options = {
            	container: null,//控件所在容器
				time: null,//控件上的结束时间
				gisId : null,//gis的ID
            	layerIds : null,//图层id
				timeInterval : null,//时间间隔，单位分钟
            	timesArr : [],//播放时间数组
				callPlay : null//播放点击事件
		};
		this.config = $.extend({},options);
		this.init(settings);
	}

    CFPlayer.prototype = {
			init : function(settings){
				this.config = $.extend(this.config, settings);
				this.$drop = bulidHtml(this.config);
				_eves(this.$drop,this.config);

                var $container = $(this.config.container);
				if($container.length > 0){
					$container.empty().append(this.$drop);
				}
			},
			setTimeArr : function(timesArr){
                this.config.timesArr = timesArr;
			}
	};
	
	CafeJS.Player = function(settings){
		var drop =new CFPlayer(settings);
		return drop;
	}
});